// 引入 react 依赖
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Text, View, Image, TouchableOpacity, ImageBackground, ScrollView, InteractionManager } from 'react-native';

// 引入第三方依赖
import _ from 'lodash';
import pureRender from 'pure-render-decorator';
import { Actions } from 'react-native-router-flux';
import Icon from 'react-native-vector-icons/Ionicons';

// antd 按需加载
import { Toast, Portal, Stepper, SwipeAction } from '@ant-design/react-native';

// 引入 处理数据 所需文件
import { getShopCartList, generateConfirmOrder, updateChecked, updateQuantity, deleteCart } from './module/module.js'

// 引入样式
import Style from './style/style.js';

// 引入公用组件
import { Status, NavBar, RnImage, RnCheckoutBox, RefreshScrollView, Results, Button } from '../../components/index.js'

// 引入专用组件
import { } from './components'

// 引入工具包
import { press, size, ScreenWidth, isLogin } from '../../util/utils.js'

class ShoppingCart extends Component {

  constructor(props) {
    super(props)
    this.state = {
      refreshing: false,
      allChecked: false,
    }
    this.getShopCartList = getShopCartList.bind(this)
    this.generateConfirmOrder = generateConfirmOrder.bind(this)
    this.updateChecked = updateChecked.bind(this)
    this.updateQuantity = updateQuantity.bind(this)
    this.deleteCart = deleteCart.bind(this)
  }

  componentDidMount() {
    // InteractionManager.runAfterInteractions(() => {
    // ...耗时较长的同步执行的任务...
    if (isLogin()) {
      this.getShopCartList({}, Toast.loading('加载中', 0, null, false)).then(res => {
        this.handleIsAllChecked()
      })
    }
    // });
  }

  componentWillReceiveProps(nextProps) {
    console.log(nextProps, 858585)

  }

  handleIsAllChecked() {
    const { shoppingCartList } = this.props
    let allChecked = false
    if (this.getShopCartCheckedList().length == shoppingCartList.cartItemList.length) {
      allChecked = true
    }
    this.setState({
      allChecked
    })
  }

  getShopCartCheckedList() {
    const { shoppingCartList } = this.props
    return shoppingCartList.cartItemList.filter(item => {
      if (item.checked) {
        return item
      }
    })
  }

  handleChecked(item, value, index) {
    const { shoppingCartList } = this.props
    this.handleUpdateChecked([item.productId], value)
  }

  handleAllChecked(allChecked) {
    const { shoppingCartList } = this.props
    this.setState({
      allChecked
    })
    this.handleUpdateChecked(shoppingCartList.cartItemList.map(item => item.productId), allChecked ? 1 : 0)
  }

  handleSubmitOrder() {
    // let shopCartCheckedList = this.getShopCartCheckedList()
    // if (shopCartCheckedList.length > 0) {
    //   // 至少选中了一个
    // } else {
    //   Toast.fail('请选择商品', 1)
    // }
    this.generateConfirmOrder().then(res => {
      Actions.submitOrders()
    })
  }

  handleUpdateQuantity(item, quantity) {
    this.updateQuantity({
      pid: item.productId,
      quantity,
    }).then(res => {
      this.getShopCartList({}, Toast.loading('加载中', 0, null, false))
    })
  }

  handleUpdateChecked(pidList, checked) {
    this.updateChecked({
      pidList: pidList,
      checked: checked ? 1 : 0,
    }).then(res => {
      console.log(res)
      this.getShopCartList({}, Toast.loading('加载中', 0, null, false)).then(list => {
        console.log(list)
        this.handleIsAllChecked()
      })
    })
  }

  onRefresh = () => {
    this.getShopCartList({}, Toast.loading('加载中', 0, null, false)).then(res => {
      this.handleIsAllChecked()
    })
  }

  handleDelete = (item) => {
    console.log(item)
    this.deleteCart({ pid: item.productId }).then(res => {
      this.getShopCartList({}, Toast.loading('加载中', 0, null, false)).then(res => {
        this.handleIsAllChecked()
      })
    })
  }

  renderContent() {
    const { shoppingCartList } = this.props
    const { refreshing, allChecked, checkedList } = this.state
    if (isLogin()) {
      return (
        <View style={{
          flex: 1
        }}>
          <RefreshScrollView
            style={Style.content}
            refreshing={refreshing}
            onRefresh={this.onRefresh}
          >
            {
              shoppingCartList.cartItemList.map((item, index) => {
                return (
                  <SwipeAction
                    key={index}
                    autoClose
                    style={{ backgroundColor: 'transparent' }}
                    right={[
                      {
                        text: '删除',
                        onPress: () => this.handleDelete(item),
                        style: { backgroundColor: 'red', color: 'white' },
                      },
                    ]}
                    onClose={() => console.log('close')}
                  >
                    <View
                      style={{
                        alignItems: 'flex-start',
                        flexDirection: 'row',
                        paddingVertical: 10,
                        borderBottomWidth: .5,
                        borderStyle: 'solid',
                        borderColor: '#ddd'
                      }}>
                      <View style={{
                        justifyContent: 'center',
                        alignItems: 'center',
                        paddingHorizontal: 15,
                        height: 75,
                      }}>
                        <RnCheckoutBox
                          value={item.checked}
                          onChange={(value) => {
                            this.handleChecked(item, value, index)
                          }}
                        />
                      </View>
                      <View style={{
                        flex: 1,
                        flexDirection: 'row',
                        alignItems: 'flex-start',
                      }}>
                        <RnImage style={{ width: 75, height: 75 }} uri={item.productPic} />
                        <View style={{
                          flex: 1,
                          paddingHorizontal: 15
                        }}>
                          <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, marginBottom: 5 }}>{item.productName}</Text>
                          <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, marginBottom: 5 }}>37%off</Text>
                          <View style={{ flexDirection: 'row', alignItems: 'center', marginBottom: 5 }}>
                            <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, marginRight: 20 }}>RM {item.price}</Text>
                            <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, textDecorationLine: "line-through", }}>RM 165.00</Text>
                          </View>
                          <View style={{}}>
                            <Stepper
                              styles={{
                                flexDirection: 'row',
                                alignItems: 'center',
                              }}
                              inputStyle={{
                                padding: 8
                              }}
                              min={1}
                              defaultValue={item.quantity}
                              onChange={(value) => {
                                this.handleUpdateQuantity(item, value)
                              }}
                            />
                          </View>
                        </View>
                      </View>
                    </View>
                  </SwipeAction>
                )
              })
            }
            {shoppingCartList.cartItemList.length <= 0 ? (
              <Results title="购物车是空的" width={size(500)} height={size(200)} />
            ) : null}
          </RefreshScrollView>
          <View style={{
            flexDirection: 'row',
            justifyContent: 'space-between',
            height: 49,
            borderTopWidth: .5,
            borderStyle: 'solid',
            borderColor: '#ddd'
          }}>
            <View style={{
              flexDirection: 'row',
              height: 49,
              alignItems: 'center',
              justifyContent: 'center',
              paddingLeft: 15
            }}>
              <RnCheckoutBox
                value={allChecked}
                onChange={(value) => {
                  this.handleAllChecked(value)
                }}
              >
                全选
            </RnCheckoutBox>
            </View>
            <View style={{
              flexDirection: 'row',
            }}>
              <View style={{
                paddingRight: 15,
                paddingTop: 5
              }}>
                <Text style={{ fontSize: 12, color: '#61676F', lineHeight: 20, textAlign: 'right' }}>不含运费</Text>
                <Text style={{ fontSize: 12, color: '#61676F', lineHeight: 20, textAlign: 'right' }}>
                  <Text style={{ fontSize: 12, color: '#61676F', lineHeight: 20, }}>合计：</Text>
                  <Text style={{ fontSize: 12, color: '#61676F', lineHeight: 20, }}>RM {shoppingCartList.productPrice}</Text>
                </Text>
              </View>
              <TouchableOpacity
                style={{
                  width: 100,
                  height: 49,
                  alignItems: 'center',
                  justifyContent: 'center',
                  backgroundColor: '#ff4f18'
                }}
                onPress={() => {
                  this.handleSubmitOrder()
                }}
              >
                <Text style={{ fontSize: 14, color: '#fff', lineHeight: 49, textAlign: 'center' }}>提交订单</Text>
              </TouchableOpacity>
            </View>
          </View>
        </View>
      )
    } else {
      return (
        <View style={{
          flex: 1,
          alignItems: 'center',
        }}>
          <View style={{
            alignItems: 'center',
            justifyContent: 'center',
            marginTop: 40,
            marginBottom: 40
          }}>
            <Button onPress={() => { Actions.login() }}>去登录</Button>
            <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 24, marginTop: 20 }}>登录后同步电脑与手机购物车中的商品</Text>
          </View>
          <Results title="购物车是空的" width={size(500)} height={size(200)} />
        </View>
      )
    }
  }

  render() {
    const { shoppingCartList } = this.props
    const { refreshing, allChecked, checkedList } = this.state
    return (
      <View style={Style.container}>
        <Status />
        <NavBar
          title="购物车"
        />
        {this.renderContent()}
      </View >
    );
  }
}


export default connect(({ shoppingCartList, userInfo }) => ({
  shoppingCartList, userInfo
}))(pureRender(ShoppingCart))
